package org.example.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author 莫磊
 * @date 2025/8/11
 * @description
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

	/**
	 * 处理器方法执行前执行，返回true表示放行，返回false表示拦截
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param handler chosen handler to execute, for type and/or instance evaluation
	 * @return
	 * @throws Exception
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		// 获取请求的url
		String url = request.getRequestURI();
		log.info("请求的url是：{}", url);

		// 获取Session
		HttpSession session = request.getSession();

		// 获取Session中的用户
		Object loginUser = session.getAttribute("loginUser");
		return true;

		// // 判断用户是否已登录
		// if (loginUser != null) {
		// 	// 已登录，放行
		// 	return true;
		// } else {
		// 	// 未登录，拦截，跳转到登录页面
		// 	request.setAttribute("msg", "请先登录");
		// 	request.getRequestDispatcher("/login").forward(request, response);
		// 	return false;
		// }
	}

	/**
	 * 页面渲染后执行
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param handler the handler (or {@link HandlerMethod}) that started asynchronous
	 * execution, for type and/or instance examination
	 * @param ex any exception thrown on handler execution, if any; this does not
	 * include exceptions that have been handled through an exception resolver
	 * @throws Exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

	/**
	 * 处理器方法执行后执行
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param handler the handler (or {@link HandlerMethod}) that started asynchronous
	 * execution, for type and/or instance examination
	 * @param modelAndView the {@code ModelAndView} that the handler returned
	 * (can also be {@code null})
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {


	}
}
